import time
import streamlit as st
from besins_selenium_downloaders.scripts import *
from besins_selenium_downloaders.config import *
from besins_selenium_downloaders.file_manager import *
from besins_selenium_downloaders.streamlit_tools import configure_page_navigation
import os
from datetime import datetime


class RunOneWebsite:
    def __init__(self):
        self.setup_page_config()
        configure_page_navigation("run_one_website")
        st.markdown(
            '<h1 class="common-title">🔄 Run One Website</h1>', unsafe_allow_html=True
        )
        self.main()

    def setup_page_config(self):
        st.set_page_config(
            page_title="Run One Website",
            page_icon="🌐",
            layout="centered",
            initial_sidebar_state="expanded",
        )

        # Load and inject CSS
        common_css_path = os.path.join(os.path.dirname(__file__), "../css/common.css")
        with open(common_css_path) as f:
            st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

        css_path = os.path.join(os.path.dirname(__file__), "../css/run_one_website.css")
        with open(css_path) as f:
            st.markdown(f"<style>{f.read()}</style>", unsafe_allow_html=True)

    def main(self):
        # Get URL parameters
        query_params = st.query_params
        default_site = query_params.get("site", get_website_names()[0])

        # Get all website names
        sites = get_website_names()
        site_task_map = map_site_to_task_id()
        site_url_map = map_site_to_url()

        # Determine the maximum length of site names for alignment
        max_site_name_length = max(len(site) for site in sites)

        # Prepare site options with SiteName | TaskID | URL
        site_options = [
            f"{site:<{max_site_name_length + 1}} | {site_task_map.get(site, 'TASK00000000')} | {site_url_map.get(site, '🌐 N/A')}"
            for site in sites
        ]

        # Sorting options with emojis
        sort_option = st.radio(
            "🔀 Sort Sites By",
            options=["Site Name", "Task ID"],
            index=0,
            horizontal=True,
        )

        if sort_option == "Site Name":
            sorted_sites = sorted(site_options, key=lambda x: x.split(" | ")[0].lower())
        else:
            sorted_sites = sorted(site_options, key=lambda x: x.split(" | ")[1])

        # Create a selectbox for choosing the site
        selected_site_display = st.selectbox(
            "🌐 Select Site to Run",
            options=sorted_sites,
            index=(
                sorted_sites.index(
                    f"{default_site:<{max_site_name_length + 1}} | {site_task_map.get(default_site, 'TASK00000000')} | {site_url_map.get(default_site, '🌐 N/A')}"
                )
                if default_site and f"{default_site:<{max_site_name_length + 1}} | {site_task_map.get(default_site, 'TASK00000000')} | {site_url_map.get(default_site, '🌐 N/A')}" in sorted_sites
                else 0
            ),
            key="site_selector",
            help="Choose which site to run",
        )

        selected_site = selected_site_display.split(" | ")[0].strip()

        self.display_site_info(selected_site)

        # Create a button to trigger the rerun with enhanced emoji
        if st.button(
            f"▶️ Run {selected_site}",
            key=f"rerun_{selected_site}",
            help="Click to start the rerun process",
            type="primary",
        ):
            self.handle_rerun(selected_site)

    def display_site_info(self, site_name):
        """Display the site configuration information in a compact and elegant layout."""
        config = load_configuration()
        site_config = config.get("websites", {}).get(site_name, {})

        # Retrieve additional configuration details
        selenium_config = config.get("selenium", {})
        dates_config = config.get("dates", {})
        headless = get_headless_mode()
        start_date = dates_config.get("start_date", "📅 Not Specified")
        end_date = dates_config.get("end_date", "📅 Not Specified")
        today = datetime.now().strftime("%Y-%m-%d")

        # Ensure end_date is a string before using strptime
        if isinstance(end_date, datetime):
            end_date = end_date.strftime("%Y-%m-%d")

        if end_date == "1111-11-11" or (
            isinstance(end_date, str)
            and datetime.strptime(end_date, "%Y-%m-%d").year < 2024
        ):
            end_date = today

        # Check if the task is performed in today's date_folder
        task_id = map_site_to_task_id().get(site_name, "🆔 TASK00000000")
        date_folder = self.get_default_folder()
        folder_exists = os.path.exists(date_folder)
        task_completed = False
        if folder_exists:
            df = get_date_folder_analysis_as_dataframe(date_folder)
            if not df.empty and site_name in df["SiteName"].values:
                task_completed = True

        # Construct the browser information
        downloader_class_name = site_name  # Assuming the class name matches the site name
        downloader_class = globals().get(downloader_class_name)
        browser_name = (
            downloader_class().browser_name if downloader_class else "🌐 Not Found"
        )

        # Define the configuration items with additional emojis
        config_items = {
            "📌 Site Name": site_name,
            "🆔 Task ID": task_id,
            "🌐 Browser": browser_name,  
            "🎭 Headless Mode": "✅ Yes" if headless else "❌ No",
            "📅 Start Date": start_date,
            "📅 End Date": end_date,
            "🔒 Captcha Required": (
                "✅ Yes" if site_config.get("captcha_required", False) else "❌ No"
            ),
            "🏆 Task Done Today": "✅ Yes" if task_completed else "❌ No",
        }

        # Use an expander for the Site Configuration section with additional emoji
        with st.expander("🛠️ Click to View Site Configuration", expanded=True):
            with st.container():
                cols = st.columns(4)
                for idx, (key, value) in enumerate(config_items.items()):
                    if idx < 4:
                        col = cols[idx]
                        col.markdown(f"**{key}**")
                        col.markdown(f"{value}")
                st.markdown("\n")
                cols = st.columns(4)
                for idx, (key, value) in enumerate(config_items.items()):
                    if idx >= 4:
                        col = cols[idx % 4]
                        col.markdown(f"**{key}**")
                        col.markdown(f"{value}")
            st.markdown("\n")
            st.markdown("🔗 **URL**: " + f"{map_site_to_url().get(site_name, '🌐 N/A')}")


    def handle_rerun(self, site_name):
        """Handle the rerun process for the selected site."""
        try:
            with st.spinner(f"🔄 Running {site_name}..."):
                run_one_website(site_name)
            st.success(f"✅ Successfully rerun {site_name}")
        except Exception as e:
            st.error(f"❌ Error running {site_name}: {str(e)}")
            st.exception(e)

    def get_default_folder(self):
        """Get the default folder based on today's date."""
        today = datetime.now().strftime("%Y-%m-%d")
        return today


if __name__ == "__main__":
    RunOneWebsite()
